package com.cw.controller;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cw.common.constant.Response;

import com.cw.config.JwtConfig;
import com.cw.entity.SysUser;
import com.cw.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * <p></p>
 * @author: ly
 * @date: 2020/10/12 09:39
 **/

@Api(tags = {"token处理"})
@RestController
@RequestMapping("/token")
public class TokenController {
    @Resource
    private JwtConfig jwtConfig;
    @Autowired
    private ISysUserService iSysUserService;

    // 拦截器直接放行，返回Token
    @ApiOperation(value = "获取token")
    @PostMapping("/getToken")
    public Response login (@RequestBody SysUser sysUser){
        Map<String,String> result = new HashMap<>(2) ;
        // 省略数据源校验
        Map<String,Object> map = new HashMap<>(2);
        final String userName = sysUser.getUsername();
        final String password = SecureUtil.md5(sysUser.getPassword());
        map.put("userName",userName);
        map.put("passWord",password);
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getUsername, userName);
        lambdaQueryWrapper.eq(SysUser::getPassword, password);
        final SysUser sysUser1 = iSysUserService.getOne(lambdaQueryWrapper);
        if(null == sysUser1){
            return new Response(500,"用户名密码错误");
        }
        lambdaQueryWrapper.eq(SysUser::getEnable, "0");
        final SysUser sysUser2 = iSysUserService.getOne(lambdaQueryWrapper);
        if(null == sysUser2){
            return new Response(500,"该用户已停用");
        }
        String token = jwtConfig.getToken(map);
        if (!StringUtils.isEmpty(token)) {
            result.put("token", token);
        }
        result.put("userName", userName);
        return new Response(result);
    }

    // 需要 Token 验证的接口
    @PostMapping("/login1/info")
    public String info() {
        Map<String, Object> map = new HashMap<>(2);
        map.put("userName", "我是");
        map.put("passWord", "123");
        final String token = jwtConfig.getToken(map);
        return token;
    }
}
